/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.msu.client.register;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import io.iec.edp.caf.commons.exception.CAFRuntimeException;
import io.iec.edp.caf.commons.exception.ExceptionLevel;
import io.iec.edp.caf.commons.exception.entity.DefaultExceptionProperties;
import io.iec.edp.caf.commons.exception.entity.ExceptionErrorCode;
import io.iec.edp.caf.commons.runtime.CafEnvironment;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.msu.api.client.ServiceUnitInfoRegistry;
import io.iec.edp.caf.msu.api.entity.MsuProperties;
import io.iec.edp.caf.msu.api.entity.ServiceUnitInfo;
import io.iec.edp.caf.msu.api.entity.ServiceUnitRegisterInfo;
import io.iec.edp.caf.msu.api.enums.DeployMode;
import io.iec.edp.caf.msu.api.server.MsuServiceRegistry;
import io.iec.edp.caf.msu.client.exception.MsuNotFoundException;
import io.iec.edp.caf.msu.client.utils.MsuConstParam;
import io.iec.edp.caf.tenancy.api.context.MultiTenantContextInfo;
import io.iec.edp.caf.tenancy.core.context.MultiTenantContextHolder;
import lombok.extern.slf4j.Slf4j;
import lombok.var;

import javax.servlet.http.Cookie;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

@Slf4j
public class ServiceUnitInfoRegisterImpl implements ServiceUnitInfoRegistry {

    private static final int DEFAULT_PORT = 5200;

    private NamingService namingService;

    public ServiceUnitInfoRegisterImpl(NamingService namingService) {
        this.namingService = namingService;
    }

    @Override
    public Boolean registerServiceUnitInfos(ServiceUnitRegisterInfo serviceUnitRegisterInfo) {
        Boolean msuRegister = false;

        try {
            MsuServiceRegistry msuServiceRegistry = SpringBeanUtils.getBean(MsuServiceRegistry.class);
            msuRegister = msuServiceRegistry.register(serviceUnitRegisterInfo);
            //msuRegister = rpcClient.invoke(Boolean.class, MsuConstParam.MSU_REGISTRY_SERVICEID, MsuConstParam.MSU_SERVICE_NAME,paramMap,eventContext);

        } catch (Exception e) {
            log.error("regist su exception",e);
            throw new MsuNotFoundException();
        }

        if (!msuRegister) {
            throw new CAFRuntimeException(DefaultExceptionProperties.SERVICE_UNIT,
                    DefaultExceptionProperties.RESOURCE_FILE,
                    ExceptionErrorCode.serviceRegisterError,
                    new String[]{},
                    null, ExceptionLevel.Error, false);
        }

        return msuRegister;

    }

    @Override
    public Boolean unRegisterServiceUnitInfos(ServiceUnitRegisterInfo serviceUnitRegisterInfo) {
        var unregisterSu = new ArrayList<ServiceUnitInfo>();
        for (ServiceUnitInfo serviceUnitInfo : serviceUnitRegisterInfo.getServiceUnitInfo()) {
            try {

                var temp = namingService.getAllInstances(serviceUnitInfo.getName().toLowerCase());

                //当前服务只有一个实例的情况下，才能注销掉msuregisterinfo表里的信息。
                if(temp.size()==1){
                    unregisterSu.add(serviceUnitInfo);
                }
            } catch (NacosException e) {
                log.error(e.getErrMsg(),e);
            }

        }

        serviceUnitRegisterInfo.setServiceUnitInfo(unregisterSu);

        try{

            //这里销毁阶段时，rest都被销毁，rpc过去会404，先暂时强制删主库数据吧
//                LinkedHashMap<String, Object> paramMap = new LinkedHashMap();
//                paramMap.put("info", serviceUnitRegisterInfo);
//                Boolean msuRegister = this.msuServerInvoker.remoteInvoke(Boolean.class, "io.iec.edp.caf.msu.api.server.MsuServiceRegistry.unRegister", paramMap);
//                if (!msuRegister) {
//                    throw new CAFRuntimeException("","","注销："+configuration.getServiceName()+","+ip+","+port+"到gspmsuregisterinfp失败",null,ExceptionLevel.Error,false);
//

            //直接链接到主库处理
            //todo 如果msu这个su不是连接到主库的，则会有问题
            //todo
            MultiTenantContextInfo contextInfo = new MultiTenantContextInfo();
            contextInfo.setMasterDb(true);
            MultiTenantContextHolder.set(contextInfo);
            MsuServiceRegistry msu = SpringBeanUtils.getBean(MsuServiceRegistry.class);
            msu.unRegister(serviceUnitRegisterInfo);
        }finally {
            MultiTenantContextHolder.set(null);
        }

        return true;

    }

}
